import '../ui/layui.all'
import '../ui/css/layui.css'
import '../ui/css/modules/code.css'
import '../ui/css/modules/layer/default/layer.css'
import '../ui/css/modules/laydate/default/laydate.css'
import './waterplay.css'
import waterimg from '../water/baseimg'
import { PolygonGeometry, PolygonHierarchy, Cartesian3,EllipsoidSurfaceAppearance, Primitive,GroundPrimitive, GeometryInstance,Material} from 'cesium';
const waterPlayer = function(views){
    this.views = views
    this.temp = '<div class="water-play-title"></div>'+
    '<div class="water-play-content">'+
        '<div class="play-group-btn">'+
            '<i class="layui-icon plat-btn layui-icon-play" data-method="playwater"></i>'+
            '<i class="layui-icon plat-btn layui-icon-pause" data-method="pausewater"></i>'+
            '<i class="layui-icon plat-btn layui-icon-release" data-method="gotowater"></i>'+
        '</div>'+
        '<div class="water-play-content-prograss">'+
            '<div class="layui-progress"  lay-showpercent="true" lay-filter="playprograss" >'+
                '<div class="layui-progress-bar" lay-percent="0%"></div>'+
            '</div>'+
       ' </div>'+
        '<div class="play-exit-btn">'+
           '<i class="layui-icon plat-btn layui-icon-close" data-method="closewater"></i> '+
        '</div>'+
    '</div>'
    this.contanner = this._drawWidget()
    this.mapping = {}
    this.PlayerInterval= window.setInterval(function () {

    })
    this.floods = null
    this.playInfo={
        prventity:null,
        state:0,   //播放状态 0 1 2
        currentIndex:0, //当前进度
        totalCount:0    //总数
    }
    this.tempentity = null
}
waterPlayer.prototype={
    openWidget:function(){
        this.contanner.style.display = true
    },
    closeWidget:function(){
        this.contanner.style.display = false
    },
    initData:function(floods){
        this.floods = floods
        this.playInfo.state = 0
        this.playInfo.currentIndex = 0
        this.playInfo.totalCount = floods.length
    },
    goto:function(){
        
    },
    play:function(){
        var self = this
        // self.playInfo.currentIndex = 60
        if(self.tempentity){
            self.views.scene.primitives.remove(self.tempentity);//添加到场景)
            self.tempentity = null
        }
        
        this.PlayerInterval= window.setInterval(function () {
            // debugger
            var flood
            self._praograss()
            if (self.floods[self.playInfo.currentIndex]) {
                flood = self.floods[self.playInfo.currentIndex];
                self.playInfo.currentIndex++
            }
            else{
                self.views.scene.primitives.remove(self.templayer);
                self.templayer=null
                self.playInfo.currentIndex = 0
                window.clearInterval(self.PlayerInterval)
                self.playInfo.state = 0
                return
            }
            for (var i = 0; i < flood.length; i++) {
                
                if(!self.templayer){
                    self.templayer = self._createWaterLayer(flood[i])
                    self.views.scene.primitives.add(self.templayer);//添加到场景
                    self.prventity = self.templayer
                }else{
                    var floodpoints = flood[i].cood.map(function(item){
                        return parseFloat(item)
                    })
                    // self.templayer.destroy()
                    // if(self.playInfo.currentIndex%2 == 0){
                        
                    // }
                    self.templayer = self._createWaterLayer(flood[i])
                    self.views.scene.primitives.add(self.templayer);//添加到场景
                    self.views.scene.primitives.remove(self.prventity);
                    // self.templayer.geometryInstances = new PolygonGeometry({
                    //     polygonHierarchy: new PolygonHierarchy(Cartesian3.fromDegreesArray(floodpoints)),
                    //     height: 320,
                    //     extrudedHeight: 0,
                    //     vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT
                    // });
                    // self.views.render()
                    // self.templayer.update()
                }
                self.prventity = self.templayer
            }

            // if (self.playInfo.prventity) {
            //     for (let j = 0; j < self.playInfo.prventity.length; j++) {
            //         self.views.scene.primitives.remove(self.playInfo.prventity[j])
            //     }
            // }
            // self.playInfo.prventity = thisFrames
        },800)
    },  
    stop:function(){
        window.clearInterval(this.PlayerInterval)
        this.playInfo.state = 0
    },  
    exit:function(){
       
    },
    _drawWidget:function(){
        var dom =  document.createElement("div");
        dom.className = "water-play";
        dom.id="waterPlayer"
        dom.innerHTML = this.temp;
        var body = document.getElementsByTagName("body")[0];
        body.appendChild(dom);
        this._bind()
        return dom
    },
    _bind:function(){
        var self = this
        //触发事件
        var active = {
            playwater:function(){
                self.play()
            },
            pausewater:function(){
                self.stop()
            },
            gotowater:function(){
                self.goto()
            },
            closewater:function(){
                self.exit()
            }
        }
        $('#waterPlayer .plat-btn').on('click', function(){
            var othis = $(this), method = othis.data('method');
            active[method] ? active[method].call(this, othis) : '';
        });
    },
    _getMaterial:function(size){
        var key = size + ""
        if (this.mapping[key])
            return this.mapping[key];

        var frequency=1
        if(size>0)
            frequency=10/Math.sqrt(size,1)
        
        var riverMaterial = new Material({
            fabric: {
                type: 'Water',
                uniforms: {
                    baseWaterColor: {
                        alpha: 1,
                        blue: 0.2,
                        green: 0.5,
                        red:  0.5,
                        // red: 0.55,
                        // green: 0.45,
                        // blue: 0.1,
                    },
                    normalMap: waterimg,
                    // normalMap:'./demo/img/water4.png',
                    frequency: 800,          // 100
                    animationSpeed: 0.01,  //0.015
                    amplitude:8   //30
                }
            }
        });
        this.mapping[key]=riverMaterial;
        return riverMaterial
    },
    _createWaterLayer:function(flood){
        if(flood.cood && flood.h && flood.a){
            var floodpoints = flood.cood.map(function(item){
                return parseFloat(item)
            })
            var polygon2 = new PolygonGeometry({
                polygonHierarchy: new PolygonHierarchy(Cartesian3.fromDegreesArray(floodpoints)),
                // extrudedHeight: flood.h,
                // perPositionHeight : true,
                height: flood.h-25, //TODO
                // vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT
            });
            var River2 = new Primitive({
                vertexCacheOptimize:true,
                geometryInstances: new GeometryInstance({
                    geometry: polygon2
                }),
                appearance: new EllipsoidSurfaceAppearance({
                    fragmentShaderSource:'varying vec3 v_positionMC;\nvarying vec3 v_positionEC;\nvarying vec2 v_st;\nvoid main()\n{\nczm_materialInput materialInput;\nvec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));\n#ifdef FACE_FORWARD\nnormalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\nmaterialInput.s = v_st.s;\nmaterialInput.st = v_st;\nmaterialInput.str = vec3(v_st, 0.0);\nmaterialInput.normalEC = normalEC;\nmaterialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);\nvec3 positionToEyeEC = -v_positionEC;\nmaterialInput.positionToEyeEC = positionToEyeEC;\nczm_material material = czm_getMaterial(materialInput);\n#ifdef FLAT\ngl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\ngl_FragColor = czm_phong(normalize(positionToEyeEC), material);\
                        gl_FragColor.a=0.5;\n#endif\n}\n'
                }),
               
                show: true
            });
            River2.appearance.material = this._getMaterial(flood.a);
            return River2
        }else{
            return null
        }
       
    },
    _praograss:function(){
        var element = layui.element
        var pgnum = (this.playInfo.currentIndex/this.playInfo.totalCount).toFixed(3)*100
        element.progress('playprograss', pgnum+'%');
    }
}
export default waterPlayer